<template>
  <a-menu 
    v-model:selectedKeys="selectedKeys" 
    :open-keys="[selectedKeys[0].substring(0, selectedKeys[0].indexOf('-'))]"
    theme="dark" 
    mode="inline" 
    @select="menuSelect">
    <a-sub-menu :title="item.value" :key="item.key" v-for="item in menuList">
      <template #icon>
        <appstore-outlined />
      </template>
      <a-menu-item :key="it.key" v-for="it in item.children">{{it.value}}</a-menu-item>
    </a-sub-menu>
  </a-menu>
</template>

<script setup lang="ts">
import router from '@/router';
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

interface MenuList {
  key: String
  value: String
  route: String
  children: MenuList[]
}

const menuList = ref<MenuList[]>(
  [{
    key: '1',
    value: '原生js',
    route: null,
    children: [{
      key: '1-1',
      value: 'radio',
      route: '/javaScript/radio',
    },{
      key: '1-2',
      value: 'checkbox',
      route: '/javaScript/checkbox',
    },{
      key: '1-3',
      value: 'popup',
      route: '/javaScript/popup',
    },{
      key: '1-4',
      value: 'switch',
      route: '/javaScript/switch',
    }]
  },{
    key: '2',
    value: 'vue3',
    route: null,
    children: [{
      key: '2-1', 
      value: 'calendar',
      route: '/vue3/calendar',
    }]
  }]
)

const selectedKeys = ref<string[]>(['1-1']);

watch(
  () => router.currentRoute.value.path,
  (curr, old) => {
  //页面刷新或初次进入时设置当前路由对应menu
  menuList.value.forEach(element => {
    element.children.forEach(ele => {
      if(ele.route == curr) {
        selectedKeys.value.splice(0,1,ele.key)
      }
    })
  })
})

const menuSelect = ({ item, key, selectedKeys }) => {
  let parentKey: String = key.substring(0, key.indexOf('-'))
  let parent: MenuList[] = []
  parent = menuList.value.find(element => {
    return element.key == parentKey
  });
  parent.children.forEach(ele => {
    if(ele.key == key) {
      router.push({
        path: ele.route
      })
    }
  });
}

</script>

<style scoped lang="less">
</style>